<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="联赛名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="联赛名称"
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="开赛时间" prop="startDate">
          <el-date-picker
            v-model="queryParams.startDate"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search/>
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh/>
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="['system:sysEventCenter:add']"
          type="success"
          @click="handleOpenDialog()"
        >
          <template #icon>
            <Plus/>
          </template>
          发布
        </el-button>
        <el-button
          v-hasPerm="['system:sysEventCenter:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon>
            <Delete/>
          </template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        :cell-style="tableCellStyle"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column type="index" label="序号" width="55" align="center"/>
        <el-table-column
          key="name"
          label="联赛名称"
          prop="name"
          min-width="250"
          align="center"
        >
          <template #default="scope">
            <div :style="{ backgroundColor: scope.row.color,width: '100%',height: '100%'}">{{ scope.row.name }}</div>
          </template>
        </el-table-column>
        <el-table-column
          key="startTime"
          label="开赛时间"
          prop="startTime"
          min-width="200"
          align="center"
        />
        <el-table-column
          key="homeTeam"
          label="主队"
          prop="homeTeam"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="patronTeam"
          label="客队"
          prop="patronTeam"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="recommend"
          label="推荐"
          prop="recommend"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="exponent"
          label="重心指数"
          prop="exponent"
          min-width="150"
          align="center"
        >
          <template #default="scope">
            <el-rate v-model="scope.row.exponent" size="large" :colors="colors" disabled/>
          </template>
        </el-table-column>
        <el-table-column
          key="score"
          label="完赛比分"
          prop="score"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="result"
          label="结果"
          prop="result"
          min-width="150"
          align="center"
        />
        <!--        <el-table-column-->
        <!--          key="createDate"-->
        <!--          label="日期"-->
        <!--          prop="createDate"-->
        <!--          min-width="150"-->
        <!--          align="center"-->
        <!--          v-show="false"-->
        <!--        />-->
        <el-table-column  key="1"  v-if="showFlag" fixed="right" label="操作" align="center" width="150">
          <template #default="scope">
            <el-button
              v-hasPerm="['system:sysEventCenter:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon>
                <Edit/>
              </template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['system:sysEventCenter:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon>
                <Delete/>
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 赛事表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="650px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="80px">
        <span class="flex flex-wrap gap-4">
          <el-form-item label="背景颜色" prop="recommend">
            <el-color-picker v-model="formData.color" show-alpha :predefine="predefineColors"/>
          </el-form-item>
         </span>
        <span class="flex flex-wrap gap-4">
          <el-form-item label="联赛名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="联赛名称"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="开赛时间" prop="startTime">
          <el-date-picker
            v-model="formData.startTime"
            style="width: 200px"
            type="datetime"
            placeholder="开赛时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        </span>

        <span class="flex flex-wrap gap-4">
         <el-form-item label="主队" prop="homeTeam">
          <el-input
            v-model="formData.homeTeam"
            placeholder="主队"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="客队" prop="patronTeam">
          <el-input
            v-model="formData.patronTeam"
            placeholder="客队"
            style="width: 200px"
          />
        </el-form-item>
        </span>

        <span class="flex flex-wrap gap-4">
        <el-form-item label="推荐" prop="recommend">
          <el-input
            v-model="formData.recommend"
            placeholder="推荐"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="重心指数" prop="exponent">
            <el-rate v-model="formData.exponent" size="large" :colors="colors"/>
        </el-form-item>
        </span>
        <span class="flex flex-wrap gap-4">
          <el-form-item label="完赛比分" prop="score">
          <el-input
            v-model="formData.score"
            placeholder="完赛比分"
            style="width: 200px"
          />
          </el-form-item>

        <el-form-item label="结果" prop="result">
          <el-input
            v-model="formData.result"
            placeholder="结果"
            style="width: 200px"
          />
        </el-form-item>
        </span>


        <!--        <el-form-item label="日期" prop="createDate">-->
        <!--          <el-date-picker-->
        <!--            style="width: 200px"-->
        <!--            v-model="formData.createDate"-->
        <!--            type="date"-->
        <!--            placeholder="日期"-->
        <!--            value-format="YYYY-MM-DD"-->
        <!--          />-->
        <!--        </el-form-item>-->

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import UserAPI, {UserInfo, UserProfileVO} from "@/api/system/user";
import SysEventCenterAPI, {
  SysEventCenterForm,
  SysEventCenterPageQuery,
  SysEventCenterPageVO
} from "@/api/system/sys-event-center";

defineOptions({
  name: "SysEventCenter",
  inheritAttrs: false,
});

const userInfo = ref<UserInfo>({});
const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const colors = ref(['#99A9BF', '#F7BA2A', '#FF9900'])
const loading = ref(false);
const showFlag = ref(true);
const removeIds = ref<number[]>([]);
const total = ref(0);
const predefineColors = ref([
  '#ff4500',
  '#ff8c00',
  '#ffd700',
  '#90ee90',
  '#00ced1',
  '#1e90ff',
  '#c71585',
  'rgba(255, 69, 0, 0.68)',
  'rgb(255, 120, 0)',
  'hsv(51, 100, 98)',
  'hsva(120, 40, 94, 0.5)',
  'hsl(181, 100%, 37%)',
  'hsla(209, 100%, 56%, 0.73)',
  '#c7158577',
])

const queryParams = reactive<SysEventCenterPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 赛事表格数据
const pageData = ref<SysEventCenterPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 赛事表单数据
const formData = reactive<SysEventCenterForm>({});

// 赛事表单校验规则
const rules = reactive({
  name: [{required: true, message: "请输入联赛名称", trigger: "blur"}],
  startTime: [{required: true, message: "请输入开赛时间", trigger: "blur"}],
  homeTeam: [{required: true, message: "请输入主队", trigger: "blur"}],
  patronTeam: [{required: true, message: "请输入客队", trigger: "blur"}],
  recommend: [{required: true, message: "请输入推荐", trigger: "blur"}],
  exponent: [{required: true, message: "请输入重心指数", trigger: "blur"}],
});

/** 查询赛事 */
function handleQuery() {
  UserAPI.getInfo().then((data) => {
    userInfo.value = data;
    const roles = userInfo.value.roles
    console.log("角色", roles)
    if (roles.includes("GUEST")) {
      showFlag.value = false;
    }
  });
  console.log("查询赛事", showFlag.value)
  loading.value = true;
  SysEventCenterAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}


/** 重置赛事查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开赛事弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改赛事";
    SysEventCenterAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增赛事";
  }
}

/** 提交赛事表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        SysEventCenterAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        SysEventCenterAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭赛事弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除赛事 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      SysEventCenterAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
